
package org.apache.solr.core;

import java.io.File;
import java.io.IOException;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockFactory;
import org.apache.lucene.store.MMapDirectory;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 *  Directly provide MMapDirectory instead of relying on {@link org.apache.lucene.store.FSDirectory#open}
 *
 * Can set the following parameters:
 * <ul>
 *  <li>unmap -- See {@link MMapDirectory#setUseUnmap(boolean)}</li>
 *  <li>maxChunkSize -- The Max chunk size.  See {@link MMapDirectory#MMapDirectory(File, LockFactory, int)}</li>
 * </ul>
 *
 **/
public class MMapDirectoryFactory extends CachingDirectoryFactory {

    private transient static Logger log = LoggerFactory.getLogger(MMapDirectoryFactory.class);
    boolean unmapHack;
    private int maxChunk;

    @Override
    public void init(NamedList args) {

        SolrParams params = SolrParams.toSolrParams(args);
        maxChunk = params.getInt("maxChunkSize", MMapDirectory.DEFAULT_MAX_BUFF);
        if (maxChunk <= 0) {
            throw new IllegalArgumentException("maxChunk must be greater than 0");
        }
        unmapHack = params.getBool("unmap", true);
    }

    @Override
    protected Directory create(String path) throws IOException {

        MMapDirectory mapDirectory = new MMapDirectory(new File(path), null, maxChunk);
        try {
            mapDirectory.setUseUnmap(unmapHack);
        }
        catch (Exception e) {
            log.warn("Unmap not supported on this JVM, continuing on without setting unmap", e);
        }
        return mapDirectory;
    }
}
